package com.spring.authManage.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.spring.authManage.pojo.RoleInfo;
import com.spring.authManage.pojo.RoleInfoParam;
import com.spring.authManage.pojo.UserInfo;
import com.spring.authManage.pojo.UserRoleInfo;
import com.spring.authManage.service.RoleInfoService;
import com.spring.authManage.service.UserInfoService;
import com.spring.common.util.AppPropertiesUtil;
import com.spring.common.util.ChunQiuTool;
import com.spring.common.util.JsonUtil;
import com.spring.common.util.MD5;

/**
 * 用户管理，用户权限分配controller层
 *
 */
@Controller("userInfoController")
@RequestMapping("/userInfo")
public class UserInfoController {
	private Logger logger=Logger.getLogger(UserInfoController.class);
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private RoleInfoService roleInfoService;
	/**
	 * 进入用户管理主页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUserInfoPage.do")
	public ModelAndView toUserInfoPage(HttpServletRequest request,
			HttpServletResponse response, UserInfo userInfo) throws Exception{
		userInfo.init(request);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//加载所有角色列表
		List<RoleInfo> roles= roleInfoService.queryAllRoleInfoByParam(null);
		resultMap.put("roles",roles);
		//加载用户列表
		UserInfo info = userInfoService.queryUserInfoByParam(userInfo);
		resultMap.put("pageResult", info.pageResult);
		return new ModelAndView("/authManage/userManage",resultMap);
	}
	
	/**
	 * 跳转到编辑页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toEditPage.do")
	public ModelAndView toEditPage(HttpServletRequest request,
			HttpServletResponse response,UserInfo userInfo) throws Exception{
		String method=ChunQiuTool.convertNull(request.getParameter("method"));
//		String id=ChunQiuTool.convertNull(request.getParameter("id"));
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(method.equals("update")){
			UserInfo info= userInfoService.queryUserInfoByUserId(userInfo.getId());
			resultMap.put("userInfo", info);
			resultMap.put("method", method);
		}
		return new ModelAndView("/authManage/userEdit",resultMap);
	}
		
	
	/**
	 * 获取所有可用角色
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/getAllRoles.do")
	public void getAllRoles(HttpServletRequest request,
			HttpServletResponse response,RoleInfoParam param) throws Exception{
		List<RoleInfo> list =null;// roleInfoService.getRoleInfosByParam(param);
		JSONArray json = JSONArray.fromObject(list);
		response.getWriter().print(json.toString());
	}
	/**
	 * 获取用户信息列表
	 * @param request
	 * @param response
	 * @param param
	 * @throws Exception 
	 */
	@RequestMapping("/listUser.do")
	public void listUser(HttpServletRequest request,
			HttpServletResponse response,UserInfo info) throws Exception{
		info.init(request);
		UserInfo userInfo = userInfoService.queryUserInfoByParam(info);
		List<UserInfo> list = userInfo.pageResult.getList();
		JSONArray json = JSONArray.fromObject(list);
		response.getWriter().print(json.toString());
	}
	/**
	 * 查询用户列表
	 * @param request
	 * @param response
	 * @param param
	 * @throws IOException 
	 */
	@RequestMapping("/queryUser.do")
	public ModelAndView queryUser(HttpServletRequest request,
			HttpServletResponse response,UserInfo info) throws Exception{
		info.init(request);
		Map<String, Object> resultMap=new HashMap<String, Object>()	;
		//加载所有角色列表
		List<RoleInfo> roles= roleInfoService.queryAllRoleInfoByParam(null);
		resultMap.put("roles",roles);
		//返回查询结果
		UserInfo userinfo = userInfoService.queryUserInfoByParam(info);
//		List list = userinfo.pageResult.getList();
		resultMap.put("pageResult", userinfo.pageResult);
		return new ModelAndView("/authManage/userManage",resultMap);
		
	}
	/**
	 * 添加更新用户
	 * @param request
	 * @param response
	 * @param info
	 * @throws IOException 
	 */
	@RequestMapping("/editUser.do")
	public ModelAndView editUser(HttpServletRequest request,
			HttpServletResponse response,UserInfo info) throws Exception {
		String method=ChunQiuTool.convertNull(request.getParameter("method"));
		info.setUpdateUser(ChunQiuTool.getUserName());
		String result = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(method.equals("update")){		
			try {
				result = this.userInfoService.updateUserInfo(info);
			} catch (Exception e) {
				logger.error("修改用户失败"+e.getMessage(),e);
				resultMap.put("method", "update");
			}
		}else{
			try {
				String defaultPassword = AppPropertiesUtil.getPropertyString("defaultpassword");
				info.setPassword(MD5.getMD5Encode(defaultPassword));
				result = this.userInfoService.addUserInfo(info);
			} catch (Exception e) {
				logger.error("新增失败"+e.getMessage(),e);
			}
		}
		if (result.equals("Y")) {
			resultMap.put("message", "success");
			if(method.equals("update")){
				logger.info(ChunQiuTool.getUserName()+"update"+ info.getRealName() + info.getUserName());
			}else{
				logger.info(ChunQiuTool.getUserName()+"insert"+ info.getRealName() + info.getUserName());

			}
		} else {
			resultMap.put("message", result);
		}			
		JsonUtil.outputJson(resultMap, response);
		return null;
	}
	
	/**
	 * 用户禁用
	 * @param request
	 * @param response
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping("/deleteUser.do")
	public ModelAndView deleteUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo info) throws Exception {
		String user_id = info.getId();
		// 作废资源
		this.userInfoService.deleteUser(user_id);
		logger.info(ChunQiuTool.getUserName()+"delete"+ info.getRealName() + info.getUserName());
		return null;
	}
	/**
	 * 重启资源
	 * @param request
	 * @param response
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping("/restartUser.do")
	public ModelAndView restartUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo info) throws Exception {
		String user_id = info.getId();
		// 重启资源
		this.userInfoService.restartUser(user_id);
		logger.info(ChunQiuTool.getUserName()+"restart"+ info.getRealName() + info.getUserName());
		return null;
	}
	
	/**
	 * 获取用户信息（根据用户ID）
	 * @param request
	 * @param response
	 * @param userId
	 */
	@RequestMapping("/getUserInfo.do")
	public void getUserInfo(HttpServletRequest request,
			HttpServletResponse response,String userId){
		
	}
	/**
	 * 获取用户权限
	 * @param request
	 * @param response
	 * @param userId
	 */
	@RequestMapping("/getUserResource.do")
	public void getUserResouce(HttpServletRequest request,
			HttpServletResponse response,String userId){
		
	}
	/**
	 * 获取用户角色,返回UserRoleInfo对象集合
	 * @param request
	 * @param response
	 * @param userId
	 */
	@RequestMapping("/getUserRoleInfo.do")
	public void getUserRoleInfo(HttpServletRequest request,
			HttpServletResponse response,String userId) throws Exception{
		List<UserRoleInfo> list=this.userInfoService.queryUserRoleInfoByUserId(userId);
		JSONArray json = JSONArray.fromObject(list);
		response.getWriter().print(json.toString());
	}
	/**
	 * 更新用户角色
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updateUserRole.do")
	public void updateUserRole(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String userId=ChunQiuTool.convertNull(request.getParameter("userId"));
		String roleIds=ChunQiuTool.convertNull(request.getParameter("roleIds"));
		String msg="";
		try {
			this.userInfoService.updateUserRole(userId, roleIds, "");
			msg="Y";
		} catch (Exception e) {
			logger.error("更新用户角色异常"+e.getMessage(),e);
			msg="N";
		}
		response.getWriter().print(msg);
	}
	/**
	 * 动态生成菜单
	 * 
	 * @param request
	 * @param response
	 * @return null
	 * @throws Exception
	 */
	@RequestMapping("/createMenu.do")
	public void createMenu(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Object[] msgs = userInfoService.getMenuByUserName(ChunQiuTool.getUserName());
		resultMap.put("menus", msgs[1]);//菜单内容
		resultMap.put("tabs", msgs[0]);//tab页名称
		JsonUtil.outputJson(resultMap, response);
	}
	/**
	 * 修改后台登陆用户密码
	 * 
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/toUpatePwdPage.do")
	public ModelAndView toUpatePwdPage(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) 
			throws Exception {
		return new ModelAndView("/authManage/changePwd");
	}
	/**
	 * 修改后台登陆用户密码
	 * 
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/updatePwd.do")
	public ModelAndView updatePwd(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String result = "";
		String userName = ChunQiuTool.getUserName();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String,Object> map=new HashMap<String, Object>();
		String password_new=ChunQiuTool.convertNull(request.getParameter("pwdnew"));
		String password_old=ChunQiuTool.convertNull(request.getParameter("password"));
		String password_confirm=ChunQiuTool.convertNull(request.getParameter("pwdconfirm"));
		map.put("password_new", password_new);
		map.put("password_old", password_old);
		map.put("password_confirm", password_confirm);
		map.put("userName",userName);
        result = this.userInfoService.updatePwd(map);
        if (result.equals("Y")) {
			resultMap.put("message", "success");
			//记入日志
			logger.info(ChunQiuTool.getUserName()+ "update" + "update password");
		} else {
			resultMap.put("message", result);
		}			
		JsonUtil.outputJson(resultMap, response);
		return null;
	}
	/**
	 * 重置密码
	 * 
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/resetPwd.do")
	public ModelAndView resetPwd(HttpServletRequest request,HttpServletResponse response) 
			throws Exception {
		String defaultPassword = AppPropertiesUtil.getPropertyString("defaultpassword");
		String id=ChunQiuTool.convertNull(request.getParameter("id"));
		defaultPassword=MD5.getMD5Encode(defaultPassword);
        this.userInfoService.resetPwd(id,defaultPassword);
		logger.info(ChunQiuTool.getUserName()+ "update" + "reset password");
		return null;
	}
}
